import { settingAIFunction } from "./settings/index"
const AIFunction: Record<string, AIFunctionItem> = {
    ...settingAIFunction()
}

const mergeIndexedObjects = <T>(data: any[]): T[] => {
    const merged = new Map();

    data.forEach(item => {
        if (!merged.has(item.index)) {
            merged.set(item.index, { ...item, function: { ...item.function } });
        } else {
            const existing = merged.get(item.index);
            existing.function.arguments += item.function.arguments;
        }
    });

    return Array.from(merged.values());
}

export const CallingFunction = async (toolCalls: tool_call[]) => {
    let tool_calls = toolCalls
    if (!toolCalls?.length) return
    if (toolCalls.length > 1) {
        tool_calls = mergeIndexedObjects<tool_call>(toolCalls);
    }
    for await (const toolCall of tool_calls) {
        if (toolCall.type === "function") {
            AIFunction[toolCall.function.name].fn(JSON.parse(toolCall.function.arguments))
        }
    }
}

export const getAllFunctionCallingTools = () => {
    const tools: any[] = []
    for (const key in AIFunction) {
        const item = AIFunction[key as keyof typeof AIFunction]
        tools.push(item.tool)
    }
    return tools
}